﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceManager.Services;
using ServiceStack.Redis;
using System.Collections;

namespace QuotationService.RealtimeQuotation
{
    class QuotationSubscribeServiceContainer
    {
        #region UsePublishService 所有的查询是否都使用行情发布服务器（一般只用于MDS行情发布端）

        private static bool _UsePublishService = false;
        /// <summary>
        /// 所有的查询是否都使用行情发布服务器（一般只用于MDS行情发布端）
        /// </summary>
        public static bool UsePublishService { get { return _UsePublishService; } set { _UsePublishService = value; } }

        #endregion

        /// <summary>
        /// 允许与每个行情查询服务器建立多少个连接；
        /// 只有在使用订阅服务器时有效;
        /// 如果使用发布服务器，则默认使用QuotationPublisher.Initialize设置的值。
        /// </summary>
        internal static Int32 ConnNumPerService = 10;

        /// <summary>
        /// 日志对象
        /// </summary>
        internal static LogService LogService = null;

        /// <summary>
        /// 查询服务
        /// </summary>
        static Dictionary<QuotationSource, QuotationSubscribeService> QueryServices = new Dictionary<QuotationSource, QuotationSubscribeService>();

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="connNumPerService">允许与每个行情查询服务器建立多少个连接；只有在使用订阅服务器时有效，如果使用发布服务器，则默认使用QuotationPublisher.Initialize设置的值。</param>
        public static void Initialize(int connNumPerService = 10)
        {
            ConnNumPerService = connNumPerService;

            //既然调用初始化，则说明不使用发布服务
            UsePublishService = false;
        }

        /// <summary>
        /// 获取查询连线
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        internal static IRedisClient GetNeedDisposedConnection(QuotationSource source)
        {
            //如果是使用发布服务器
            if (UsePublishService)
            {
                var publisher = QuotationPublishServiceContainer.GetPublishService(source);
                if (publisher == null)
                    return null;

                return publisher.GetNeedDisposedConnection();
            }

            //如果使用订阅服务器
            else
            {
                lock (((ICollection)QueryServices).SyncRoot)
                {
                    QuotationSubscribeService service = null;

                    if (!QueryServices.TryGetValue(source, out service))
                    {
                        service = DirectoryService.GetQuotationSubscribeService(QuotServiceNames.PubServicePrefix + source, ConnNumPerService);
                        if (service == null)
                            return null;

                        QueryServices[source] = service;
                    }

                    return service.GetNeedDisposedConnection();
                }
            }
        }
    }
}
